﻿using System;
using System.Collections;
using System.Data;
using BP.DA;
using BP.Sys;
using BP.CCBill;
using BP.Web;
using Newtonsoft.Json;
using System.Text.Json.Nodes;

namespace BP.App.Demo
{
    /// <summary>
    /// 业务单元基类
    /// 1. 重写该类为业务单元子类.
    /// 2. 每个业务单元子类可以在流程事件节点时间设置.
    /// 3. 被继承的子类的必须在BP.*.DLL 里面,才能确保设置时候被映射到.
    /// 4. 子类在DoIt方法中根据WorkID 的书写业务逻辑.
    /// </summary>
    public class BuessUnit_fsjma_GenerToken : BuessUnitBase
    {
        public override string Title
        {
            get
            {
                return "GenerToken:获取[方策]数据源的Token";
            }
        }

        /// <summary>
        /// 执行的方法,获取token.
        /// </summary>
        public override string DoIt()
        {
            string passWord = DBAccess.RunSQLReturnStringIsNull("SELECT Pass FROM Port_Emp WHERE No='" + WebUser.No + "'", null);
            if (passWord == null)
                throw new Exception("err@用户不存在或者没有密码.");

            string url = "http://comms.fsjma.cn:8089/CommonAppServer/Account/Login?commstest=XCDemo";
            string userNo = "fccgy"; // WebUser.No;
            string userName = "方策-陈刚毅"; // WebUser.Name;
            string userType = "comms";
            passWord = "chan9808";

            string pwd = userNo + DBAccess.GenerMD5(userNo.ToLower(), true) + DBAccess.GenerMD5(passWord, true);
            JsonObject json = new JsonObject();
            json.Add("AppName", "Web");
            json.Add("UniqueID", DBAccess.GenerGUID());

            json.Add("UserType", userType);
            json.Add("UserID", userNo);
            json.Add("Pwd", pwd);

            string bodyData = json.ToString();
            string header = "{md5:'" + DBAccess.GenerMD5(bodyData) + "'}";

            //通过下面的方法获取token.
            string data = BP.Tools.PubGlo.HttpPostConnect(url, bodyData, "POST", true, header);
            if (DataType.IsNullOrEmpty(data) == true)
                throw new Exception("err@获取token错误,data为空 url:" + url + ", bodyData=" + bodyData + "  header=" + header);

            dynamic jsonFS = JsonConvert.DeserializeObject(data);
            if (jsonFS != null)
            {
                if (jsonFS.code != 0)
                    throw new Exception("err@密码或者用户名错误，数据:" + data);
                return jsonFS.data.accessToken;
            }
            throw new Exception("err@获取token错误:" + data + " url:" + url + ", bodyData=" + bodyData + "  header=" + header);
        }
    }
}
